package com.plum.admin.modules.social.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.modules.social.entity.SysSocial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/10/12 16:15
 */
@Component
@Slf4j
public class GiteeLoginService {

    @Value("${social.gitee.appId}")
    private String appId;

    @Value("${social.gitee.client_secret}")
    private String clientSecret;
    /**
     * gitee授权地址
     */
    private static final String AUTHORIZE_URL="https://gitee.com/oauth/authorize";
    /**
     *获取token地址
     */
    private static final String ACCESS_TOKEN_URL="https://gitee.com/oauth/token?grant_type=authorization_code";
    /**
     * 获取用户信息地址
     */
    private static final String USER_INFO_URL="https://gitee.com/api/v5/user";

    public String getAuthorizeUrl(String callbackUrl){
        StringBuilder url=new StringBuilder();
        url.append(AUTHORIZE_URL)
                .append("?client_id=").append(appId)
                .append("&redirect_uri=").append(callbackUrl)
                .append("&response_type=code");
        return url.toString();
    }

    public String getAccessToken(String code,String callbackUrl){
        StringBuilder url=new StringBuilder();
        url.append(ACCESS_TOKEN_URL)
                .append("&code=").append(code)
                .append("&client_id=").append(appId)
                .append("&redirect_uri=").append(callbackUrl);
        String result = HttpUtil.post(url.toString(), Map.of("client_secret",clientSecret));
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }
    public SysSocial getUserInfo(String token){
        StringBuilder url=new StringBuilder();
        url.append(USER_INFO_URL)
                .append("?access_token=").append(token);
        String result = HttpUtil.get(url.toString());
        JSONObject jsonObject = JSONObject.parseObject(result);
        SysSocial social=new SysSocial();
        social.setOpenId(jsonObject.getString("id"));
        social.setNickName(jsonObject.getString("name"));
        social.setAvatar(jsonObject.getString("avatar_url"));
        social.setPlatform(Constant.SOCIAL_TYPE_GITEE);
        return social;
    }
}
